package com.example.demo.scheduledtask;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.example.demo.common.Constant;
import com.example.demo.config.ErpConfig;
import com.example.demo.mapper.AsyncWorkorderMapper;
import com.example.demo.mapper.PoMpsinfoMapper;
import com.example.demo.mapper.WmsPurchaseMapper;
import com.example.demo.utils.SoapXmlUtil;
import com.example.demo.vo.CompleteInVo;
import com.example.demo.vo.CompleteInVoReceiptListReq;
import com.example.demo.vo.CompleteInVoReceiptListVo;
import com.example.demo.vo.XmlResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

/**
 * @author : Zhang.yt
 * @date : 2024/7/29
 */
@Component
@Slf4j
@DS("wms")
public class CompleteInCallback {
    @Resource
    private WmsPurchaseMapper wmsPurchaseMapper;

    @Autowired
    private SoapXmlUtil soapXmlUtil;

    @Autowired
    PoMpsinfoMapper poMpsinfoMapper;

    @Resource
    private ErpConfig erpConfig;



    /**
     * 生产完工入库-成品入库-提交时不自动审核，过账成功后自动审核，做卡控防止数据出现问题
     */
//    @Scheduled(cron = "30 0/2 * * * ?")//开启定时同步
    @Scheduled(fixedDelay = 9 * 1000)//开启定时同步
    //@Async(value = "taskExecutor")
    public void completeInCallback() {
        //查询没有回调的数据
        CompleteInVo completeInVo = wmsPurchaseMapper.getCompleteInCallback();

//        List<String> innoList = completeInCallback.stream().map(CompleteInVo::getSfeaud005).collect(Collectors.toList());
        if (ObjectUtils.isEmpty(completeInVo) || ObjectUtils.isEmpty(completeInVo.getSfeaud005())) {
            log.info("未查询到生产完工入库数据，修改错误单据重试");
            wmsPurchaseMapper.completeInCallbackLose();
            return;
        }
        //捕获异常，设置单据状态为失败，避免总是取到该单据导致后续任务无法处理
        try {
            //超过20秒未获取到锁就退出
//            if (!lock.tryLock(17, TimeUnit.SECONDS)) {
//                return;
//            }

            String sfeaud005 = completeInVo.getSfeaud005();
            //根据没有回调的数据查询细表
            List<CompleteInVoReceiptListVo> completeInVoReceiptList = wmsPurchaseMapper.getCompleteInReceiptListCallback(sfeaud005);
            Map<String, List<CompleteInVoReceiptListVo>> listMap = completeInVoReceiptList.stream().collect(Collectors.groupingBy(CompleteInVoReceiptListVo::getInno));
//        for (CompleteInVo completeInVo : completeInCallback) {
            completeInVo.setActionType(Constant.ActionType_I);
            completeInVo.setSfeadocno(Constant.PMDSDOCNO_5701);
            completeInVo.setSfeasite(Constant.PMDSSITE_AMA);
            List<CompleteInVoReceiptListVo> completeInVoReceiptListVos = listMap.get(completeInVo.getSfeaud005());
            List<CompleteInVoReceiptListReq> completeInVoReceiptListReqs = BeanUtil.copyToList(completeInVoReceiptListVos, CompleteInVoReceiptListReq.class);
            //查询工单已入回填数量
            String sfeb001 = completeInVoReceiptListReqs.get(0).getSfeb001();

            int completeInCallbackRunCard = wmsPurchaseMapper.getCompleteInCallbackRunCard(sfeb001);
            //老数据按erp现在的项次计算
            Integer completeInCallbackRunCardInno = wmsPurchaseMapper.getCompleteInCallbackRunCardInno(completeInVo.getSfeaud005());
            if (ObjectUtil.isNotEmpty(completeInCallbackRunCardInno) && completeInCallbackRunCardInno != 0) {
                completeInCallbackRunCard = completeInCallbackRunCardInno;
            }

            //封装runcard
//            for (int i = 0; i < completeInVoReceiptListReqs.size(); i++) {
//                completeInVoReceiptListReqs.get(i).setSfeb026(completeInCallbackRunCard + i);
//            }
            for (CompleteInVoReceiptListReq completeInVoReceiptListReq : completeInVoReceiptListReqs) {
                //根据批号截取项次
                completeInCallbackRunCard++;
                completeInVoReceiptListReq.setSfeb026(completeInCallbackRunCard);
            }

            String resMessage = soapXmlUtil.getSoapXml("WorkOrderin", "sfea_t", "sfeb_t", completeInVo, completeInVoReceiptListReqs);
            try {
                //转换为soap消息
                log.info("生产完工入库请求数据->{}", resMessage);

                //发送soap消息，并解析结果
                //修改状态为3 erp待返回
                wmsPurchaseMapper.updateWorkOrderinCallback(completeInVo.getSfeaud005(), "数据反写中", 3);
                String result;
                try {
                    result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
                } catch (Exception e) {
                    result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
                }
                //调用等待
                if (completeInVoReceiptListReqs.size() >= 50) {
                    Thread.sleep(60 * 1000);
                } else if (completeInVoReceiptListReqs.size() >= 30) {
                    Thread.sleep(30 * 1000);
                } else if (completeInVoReceiptListReqs.size() >= 10) {
                    Thread.sleep(5 * 1000);
                }
                log.info("soap接口生产完工回调->{}", result);
                XmlResp xmlResp = soapXmlUtil.analysisXml(result);
                if (xmlResp.getCode().equals("0")) {
                    //更新相应表状态为已下发
                    wmsPurchaseMapper.updateWorkOrderinCallback(completeInVo.getSfeaud005(), xmlResp.getData().get("sfeadocno"), 1);
                    //更新入库单状态信息
                    wmsPurchaseMapper.updateStInstoreCp(completeInVo.getSfeaud005());
                } else {
                    //更新相应表状态为已下发
                    wmsPurchaseMapper.updateWorkOrderinCallback(completeInVo.getSfeaud005(), xmlResp.getMessage(), 2);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
//        }
        } catch (Exception e) {
            wmsPurchaseMapper.updateWorkOrderinCallback(completeInVo.getSfeaud005(), "非常见的数据处理问题，请联系开发人员处理", 2);
            e.printStackTrace();
        }
//        finally {
//            log.error("finally释放锁{}", this.getClass().getName());
//            if (ObjectUtil.isNotEmpty(lock) && lock.isHeldByCurrentThread()) {
//                lock.unlock();
//            }
//        }


    }
}
